<template>
  <el-dialog
    title="新加角色"
    :visible.sync="dialogVisible"
    :close-on-click-modal="false"
    :show-close="false"
  >
    <el-form
      :model="form"
      :rules="rules"
      ref="ruleForm"
      label-width="100px"
      size="small"
      class="form-box"
    >
      <el-form-item label="角色" prop="role">
        <el-select v-model="form.role" @change="changeSelect" placeholder="请选择角色">
          <el-option
            v-for="option in options"
            :label="option.role"
            :value="option.role"
            :key="option.key"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="请输入账号" prop="username">
        <el-input v-model="form.username" placeholder="请输入账号"></el-input>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="$emit('closeDialog')">取消</el-button>
      <el-button @click.native.prevent="handleAdd" type="primary">确定</el-button>
    </div>
  </el-dialog>
</template>
<script lang="ts">
import { Component, Vue, Provide, Prop } from "vue-property-decorator";

@Component({
  components: {}
})
export default class AddAccount extends Vue {
  @Provide() formLabelWidth: number = 120; //搜索框
  // 属性或参数中使用 ！：表示强制解析（告诉typescript编译器，这里一定有值），常用于vue-decorator中的@Prop
  @Prop(Boolean) dialogVisible!: boolean;
  @Prop(Array) options!: Array<string>;
  @Provide() rules = {
    username: [{ required: true, message: "请输入账号", trigger: "blur" }],
    role: [{ required: true, message: "请选择角色", trigger: "change" }]
  };
  @Provide() form: object = {
    key: "",
    role: "",
    username: "",
    des: ""
  };
  handleSubmit() {
    (this as any).$axios
      .post()
      .then((res: any) => {
        (this as any).$message({
          message: res.data.msg,
          type: "success"
        });
        this.$emit("closeDialog");
      })
      .catch((error: any) => {});
  }
  changeSelect(select: string): void {
    console.log(select);
    //先遍历数组 如果 角色等于 选中的 值  给 key  des  赋值
    this.options.map((option: any) => {
      if (option.role == select) {
        (this as any).form.key = option.key;
        (this as any).form.des = option.des;
      }
    });
  }
  //添加角色
  handleAdd() {
    // console.log(this.account);
    (this as any).$refs["ruleForm"].validate((valid: boolean) => {
      if (valid) {
        (this as any).$axios
          .post("/api/users/addUser", this.form)
          .then((res: any) => {
            this.$emit("update");
            (this as any).$message({
              message: res.data.msg,
              type: "success"
            });
          }).catch((error:any)=>{
              (this as any).$message({
              message: '添加用户失败',
              type: "error"
            });
          });
      }
    });
  }
}
</script>
<style lang="scss">
.form-box {
  .el-input,
  .el-select {
    width: 200px !important;
  }
}
</style>